<template>
  <el-form :inline="true" :model="formData" class="demo-form-inline">
    <el-form-item label="客户：">
      <el-select v-model="formData.erpSupplier.supName" clearable style="width: 310px; margin-left: 10px;"
        placeholder="请选择客户">
        <el-option v-for="customer in show" :key="customer.id" :label="customer.supName" :value="customer.supId" />
      </el-select>


    </el-form-item>

    <el-form-item label="单据编号">
      <el-input v-model="formData.billNo" placeholder="自动生成单据编号" readonly></el-input>
    </el-form-item>

    <el-form-item label="创建时间">
      <el-date-picker type="datetime" placeholder="选择日期与时间" clearable class="input" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </el-form-item>

    <el-form-item label="财务人员：">
      <el-select v-model="formData.erpPerson.perName" clearable style="width: 200px; margin-left: 10px;"
        placeholder="请选择财务人员">
        <el-option v-for="persons in person" :key="persons.perId" :label="persons.perName" :value="persons.perId" />
        <el-option :value="undefined" disabled style="cursor: pointer">
          <el-button type="text" v-perm:finance:revenue:insert:financestaff="insert">
            <i class="el-icon-menu"></i>新增财务人员
          </el-button>
        </el-option>
      </el-select>
    </el-form-item>
    <el-button type="primary" class="ant-btn ant-btn-primary" style="margin-right: 10px;" plain
      v-perm:finance:receivables:collectionchoose="insert">
      <el-icon class="el-icon-left">
        <Plus />
      </el-icon>
      <span>选择单据</span>
    </el-button>
    <el-table :data="tableData" show-summary style="width: 100%">

      <el-table-column v-if="showIdColumn" label="id" width="400">
        <template #default="{ row }">
          <el-input v-model="row.id"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单据编号" width="400">
        <template #default="{ row }">
          <el-input v-model="row.number" placeholder="请输入单据编号"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="应收欠款" width="400">
        <template #default="{ row }">
          <el-input v-model="row.je" placeholder="请输入营收欠款"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="已收欠款" width="400">
        <template #default="{ row }">
          <el-input v-model="row.qk" placeholder="请输入已收欠款"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="本次收款" width="400">
        <template #default="{ row }">
          <el-input v-model="row.sk" placeholder="请输入已收欠款"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="400">
        <template #default="{ row }">
          <el-input v-model="row.bz" placeholder="请输入备注"></el-input>
        </template>
      </el-table-column>
    </el-table>


    <div class="index-body zb">
      <el-form-item label="收款账户：" style="margin-right: 120px;">
        <el-select clearable style="width: 200px;" placeholder="请选择账户" v-model="formData.erpAccount.accId">
          <el-option v-for="account in accounts" :key="account.id" :label="account.name" :value="account.accId" />
        </el-select>
      </el-form-item>

      <el-form-item label="合计收款：" style="margin-right: 100px;">
        <el-input style="width: 240px" :value="totalReceived" readonly></el-input>
      </el-form-item>


      <el-form-item label="优惠金额：" style="margin-right: 100px;">
        <el-input style="width: 240px" v-model="discountAmount"></el-input>
      </el-form-item>
      <el-form-item label="实际收款：" style="margin-right: 100px;">
        <el-input style="width: 240px" :value="actualReceived" readonly></el-input>
      </el-form-item>

    </div>

    <div class="ant-coloery" style="margin-right: 10px;">
      <el-form-item label="附件：">
        <el-button plain>
          <el-icon style="margin-right: 10px;">
            <MessageBox />
          </el-icon>上传附件
        </el-button>
      </el-form-item>
    </div>
  </el-form>

  <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="80%"
    style="margin-left: 250px; margin-top: 200px">
    <router-view @close="close" :data="data" :supId="ruleForm.supId"></router-view>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, defineProps } from 'vue';
import router from '@/router';
import request from '@/api/request';
import { ElMessage } from 'element-plus';
import { computed } from 'vue';
import { sk } from 'element-plus/es/locale';

const totalReceived = computed(() => {
  return tableData.value.reduce((sum, row) => sum + (parseFloat(row.sk) || 0), 0);
});
const discountAmount = ref(0);

const actualReceived = computed(() => {
  const total = totalReceived.value;
  return total - discountAmount.value;
});
let props = defineProps(["data"]);
console.log(props.data);
let formData = ref({ ...props.data });


const visible = ref(false);
const title = ref("");
const data = ref({});
const ruleForm = ref({
  supId: '',
  linkNumber: '',
  number: '',
  organId: '',
  accountId: '',
  handsPersonId: '',
  discountAmount: '',
  actualReceived: ''
});

const close = () => {
  visible.value = false;
};

const tableData = ref([{ barCode: '', categoryName: '', color: '' }]);

const addRow = () => {
  tableData.value.push({
    barCode: '',
    categoryName: '',
    color: '',
  });
};
const show = ref([]);
const loadCushowstomers = () => {
  request({
    url: '/basic/vendor/list',
    method: 'get'
  }).then(res => {

    show.value = res.data; // 更新客户数据
  }).catch(err => {
    console.error(err);
  });
};
loadCushowstomers();
const accounts = ref([]);
const loadAccounts = () => {
  request({ url: '/basic/account/list', method: 'get' })
    .then(res => accounts.value = res.data)
    .catch(err => console.error(err));
};
loadAccounts();
const submitForm = () => {
  const totalAmount = tableData.value.reduce((sum, row) => sum + (parseFloat(row.je) || 0), 0);
  const changeAmount = tableData.value.reduce((sum, row) => sum + (parseFloat(row.sk) || 0), 0);
  const data = {
    erpAccountHead: {
      billNo: formData.value.billNo,
      organId: formData.value.erpSupplier.supId,
      creator: '1',
      accountId: formData.value.erpAccount.accId,
      handsPersonId: formData.value.handsPersonId,
      changeAmount: totalAmount,
      totalPrice: totalAmount,
      status: '0'
    },
    erpAccountItems: tableData.value.map(row => ({
      id: row.id,
      remark: row.bz || '',
      billId: row.id,
      eachAmount: row.sk,
      needDebt: row.je,
      finishDebt: row.qk,
    })),
  };


  request({
    url: '/accountHead/update',
    method: 'put',
    params: { billNo: formData.value.billNo },
    data: data,
    headers: { 'Content-Type': 'application/json' },
  }).then(res => {
    console.log(res);
    ElMessage.success('提交成功');
  }).catch(err => {
    console.error(err);
    ElMessage.error('提交失败: ' + (err.message || '请稍后重试'));
  });
};

const handleSave = (selectedItems) => {
  console.log('选中的数据:', selectedItems);
  // 进一步处理选中的数据
};



let save = ref([]);

// 清空现有的行
tableData.value = [];




function deepClone(data) {
  return JSON.parse(JSON.stringify(data));
}

// 在 onMounted 或 loadTableData 中更新 tableData
const loadTableData = () => {
  tableData.value = deepClone(formData.value.erpAccountItems).map(item => ({
    id: item.id,

    number: item.number,
    je: item.eachAmount || 0,
    bz: item.bremark || '',
    qk: Math.abs(item.needDebt) || 0 - Math.abs(item.finishDebt) || 0,
    sk: item.eachAmount || 0,
  }));
};

loadTableData();
console.log(formData.value.erpAccountItems[0].number);


const customers = ref([]); // 存储客户数据  

const loadCustomers = () => {
  request({ url: '/basic/vendor/findBy', method: 'get' })
    .then(res => {
      console.log(res);
      customers.value = res.data; // 更新客户数据  
    }).catch(err => {
      console.error(err);
    });
};
loadCustomers();

const person = ref({});
const personfin = () => {
  request({ url: '/basic/person/list', method: 'get' })
    .then(res => {
      person.value = res.data;
      console.log(res);
    });
}
personfin();

const insert = (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
  personfin();
};

// 页面加载时生成订单编号  
onMounted(() => {
  let currentOrderNumber = parseInt(localStorage.getItem('orderNumber') || '1', 10);
  currentOrderNumber++;
  const formattedOrderNumber = currentOrderNumber.toString().padStart(10, '0');
  ruleForm.value.number = formattedOrderNumber;
  localStorage.setItem('orderNumber', currentOrderNumber.toString());
});
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>